package com.hspedu.search;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Charlie
 * @version 1.0
 * @date 29/10/2025 下午3:01
 */
public class BinarySearch {
    public static void main(String[] args) {
        int arr[] = {1,8,10,89,89,1000,1234};

        ArrayList list = binarySearch2(arr,0,arr.length-1,89);
        System.out.println("resIndex ="  + list);
    }

    public static int binarySearch(int[] arr , int left, int right, int findValue){
        int mid = (left+right)/2;
        int midVal =arr[mid];
        int temp [] = new int[arr.length];
        int index = 0 ;
        if(left<=right){
        if(findValue>midVal){ //向右递归
            return binarySearch(arr,mid+1,right,findValue);

        }else if(findValue<midVal){
            return binarySearch(arr,left,mid-1,findValue);

        }else {
           return mid;
        }
    } else{
          return -1;
        }
    }


    public static ArrayList binarySearch2(int[] arr , int left, int right, int findValue){
        int mid = (left+right)/2;
        int midVal =arr[mid];


        if(left<=right){
            if(findValue>midVal){ //向右递归
                return binarySearch2(arr,mid+1,right,findValue);

            }else if(findValue<midVal){
                return binarySearch2(arr,left,mid-1,findValue);

            }else {
                ArrayList<Integer> integers = new ArrayList<Integer>();
                int temp = mid -1;
                while (true){
                    if(temp<0||arr[temp]!=findValue){
                        break;
                    }
                    integers.add(temp);
                    temp--;
                }
                integers.add(mid);

                 temp = mid +1;
                while (true){
                    if(temp> arr.length-1||arr[temp]!=findValue){
                        break;
                    }
                    integers.add(temp);
                    temp++;
                }

                return integers;


            }
        } else{
            return null;
        }
    }

}
